package org.jeecg.modules.qiangzlw.Job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.qiangzdygx.entity.AgQiangzdygx;
import org.jeecg.modules.qiangzdygx.service.IAgQiangzdygxService;
import org.jeecg.modules.qiangzlw.entity.AgQiangzlw;
import org.jeecg.modules.qiangzlw.entity.DetaQiangZLWRecord;
import org.jeecg.modules.qiangzlw.service.IAgQiangzlwService;
import org.jeecg.modules.shextdj.entity.DetaShextData;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

@Slf4j
public class syncQiangzlw implements Job {
    @Value("${deta.serverUrl}")
    String serverUrl = "";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {

            log.info(" 同步枪支离位记录，任务执行结束了，执行时间:" + DateUtils.formatDateTime());
            long t1 = System.currentTimeMillis();
            syncDeta();
            long t2 = System.currentTimeMillis();
            log.info(" 同步枪支离位记录，任务执行结束了，执行时间:" + (t2-t1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private IAgQiangzlwService agQiangzlwService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private IAgQiangzdygxService agQiangzdygxService;
    boolean yetFinishSync = false;

    // 同步德塔枪支离位数据
    public Result <?> syncDeta() throws Exception {
        System.out.println("同步德塔枪支离位数据");
        // 如果上次没同步完，直接返回
        if (yetFinishSync) {
            System.out.println("yet over");
            return null;
        }

        Map <String, Object> map = new HashMap <>();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("page", 1);
        map2.put("size", 5000);
        map.put("pagination", map2);

        map2 = new HashMap<>();
        map2.put("direction", "DESC");
        List list2 = new ArrayList();
        list2.add("newtime");
        map2.put("fields", list2);
        map.put("sort", map2);

        map2 = new HashMap<>();
        Map map3 = new HashMap<String, Object>() {
            {
               // put("field", "new_time");
                //put("ops", "gt");
                put("field", "newtime");
                put("ops", "ge");

                long shijc = DateUtils.str2Timestamp("2020-01-01 00:00:00").getTime();
                AgQiangzlw agQiangzlw = agQiangzlwService.getOne(new QueryWrapper<AgQiangzlw>().orderByDesc("shangbsj"), false);

                if(agQiangzlw != null) {
                    System.out.println(DateUtils.formatTime(agQiangzlw.getShangbsj()));
                    shijc = DateUtils.getTimestamp(agQiangzlw.getShangbsj()).getTime();
                }

                put("value", shijc);
            }
        };

        List list = new ArrayList<>();
        list.add(map3);
        map2.put("and", list);
        map.put("filter", map2);
        map.put("t", DateUtils.getTimestamp());

        System.out.println(JSONObject.toJSON(map).toString());
        DetaShextData detaShextData = restTemplate.postForObject(serverUrl + "/dw/httpqzlw", map, DetaShextData.class);

        if (detaShextData != null) {
            List<AgQiangzlw> batch = new ArrayList<>();
            System.out.println(detaShextData.getRecords().size());

            for (String str : detaShextData.getRecords()
            ) {
                DetaQiangZLWRecord detaQiangZLWRecord = JSON.parseObject(str, new TypeReference <DetaQiangZLWRecord>() {
                });
                if (detaShextData != null) {
                    AgQiangzlw agQiangzlw = new AgQiangzlw();

                    agQiangzlw.setDianzbq(detaQiangZLWRecord.getQZ_id());
                    AgQiangzdygx agQiangzdygx = agQiangzdygxService.getOne(new QueryWrapper <AgQiangzdygx>().eq("dianzbq", agQiangzlw.getDianzbq()), false);
                    if(agQiangzdygx != null)
                        agQiangzlw.setQiangzbh(agQiangzdygx.getQiangzbh());

                    if(detaQiangZLWRecord.getWarning_type() != null && !detaQiangZLWRecord.getWarning_type().equals(""))
                        agQiangzlw.setQiangzlwzt(detaQiangZLWRecord.getWarning_type());
                    if(detaQiangZLWRecord.getAlarm_type().equals("离位告警"))
                        agQiangzlw.setQiangzlwzt("4");

                    agQiangzlw.setBeiz(detaQiangZLWRecord.getAlarm_description());

                    long timestamp = Long.parseLong(detaQiangZLWRecord.getAlarm_time());
                    LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
                    agQiangzlw.setShangbsj(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
                    agQiangzlw.setCreateTime(new Date());

                    agQiangzlw.setGpsJingd(detaQiangZLWRecord.getLongitude());
                    agQiangzlw.setGpsWeid(detaQiangZLWRecord.getLatitude());


                    if(detaQiangZLWRecord.getWarning_distance().equals("")){
                        agQiangzlw.setYujjl(null);}
                    else{
                        agQiangzlw.setYujjl(detaQiangZLWRecord.getWarning_distance());}

                    batch.add(agQiangzlw);
                }
            }

            try {
                yetFinishSync = true;
                agQiangzlwService.saveBatch(batch, 5000);

            } catch (Exception error) {
                System.out.println(error.getMessage());
            } finally {
                yetFinishSync = false;
            }

            return Result.ok();
        }

        return Result.error("同步数据失败");
    }

}
